package com.example.restaurant.controller.component;




import com.example.restaurant.common.RestaurantException;
import com.example.restaurant.common.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        e.printStackTrace();
        return Result.error();
    }
    @ExceptionHandler(RestaurantException.class)
    public Result handleException(RestaurantException e){
        e.printStackTrace();
        return Result.error("501",e.getMessage());
    }
    @ExceptionHandler(BindException.class)
    public Result handleBindException(BindException e) {

        StringBuilder errorMsgBuilder = new StringBuilder();
        List<FieldError> fieldErrors = e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMsgBuilder.append(fieldError.getField() + ":" + fieldError.getDefaultMessage() + ";");
        }

        return Result.error("400", errorMsgBuilder.toString());
    }

}
